
//
//  DataBaseTool.m
//  Travel
//
//  Created by lanou3g on 15/12/17.
//  Copyright © 2015年 涂晓雨. All rights reserved.
//

#import "DataBaseTool.h"

@implementation DataBaseTool
+(instancetype)shareDataBaseTool{
    static DataBaseTool *dataBase = nil;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        dataBase = [[DataBaseTool alloc]init];
    });
    return dataBase;
}


#pragma mark------------------创建数据库  并打开数据库
-(void)openDataBase{
    
    //指定存储的路径
    NSString *path = NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES)[0];
    NSLog(@"%@",path);
    //指定数据存储的文件名
    NSString *filePath = [path stringByAppendingPathComponent:@"base.sqlite"];
    //创建一个数据库，并且会打开数据库
    self.db = [FMDatabase databaseWithPath:filePath];
    BOOL flag = [self.db open];
    if (flag) {
        NSLog(@"打开成功");
    }else{
        
        NSLog(@"打开失败");
    }
    
    
    //创建一个数据库表（用户表）
    BOOL flag1 = [self.db executeUpdate:@"create table if not exists t_news (id integer primary key autoincrement,name text,password text)"];
    if (flag1) {
        NSLog(@"创建成功");
    }else{
        
        NSLog(@"创建失败");
    }
    
    
    //创建一个数据库表（收藏表）
    BOOL flag2 = [self.db executeUpdate:@"create table if not exists t_contact (id integer primary key autoincrement,title text)"];
    if (flag2) {
        NSLog(@"创建成功");
    }else{
        
        NSLog(@"创建失败");
    }
}




//增加

-(void)insertWithModel:(UserModel *)model{
    BOOL flag = [self.db executeUpdate:@"insert into t_news(name,password) values (?,?)",model.name,model.password];
    if (flag) {
        NSLog(@"插入成功");
    }else{
        
        NSLog(@"插入失败");
    }
}


//查找所有的
-(NSArray *)selectAllUser{
    FMResultSet *set = [self.db executeQuery:@"select * from t_news"];
    NSMutableArray *users = [NSMutableArray array];
    while ([set next]) {
        
        self.user = [[UserModel alloc]init];
        self.user.name = [set stringForColumn:@"name"];
        self.user.password = [set stringForColumn:@"password"];
        [users addObject:self.user];
    }
    return users;
}

//查询登陆的数据是否存在
-(BOOL)searchUserData:(UserModel *)model{
    
    FMResultSet *set = [self.db executeQuery:@"select * from t_news"];
    while (set.next) {
        UserModel *model1 = [[UserModel alloc]init];
        model1.name = [set stringForColumn:@"name"];
        model1.password = [set stringForColumn:@"password"];
        if ([model1.name isEqualToString:model.name] && [model1.password isEqualToString:model.password]) {
            return YES;
        }
    }
    return NO;
}


@end
